package com.wang.bootbuilder.aop;

import com.wang.bootbuilder.annotation.HasPermission;
import com.wang.bootbuilder.entity.pojo.SessionUser;
import com.wang.bootbuilder.execption.NotHasPermissionException;
import com.wang.bootbuilder.tools.JsonResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Arrays;

@Aspect
@Component
public class PermissionAop {

    @Around("@annotation(com.wang.bootbuilder.annotation.HasPermission)")
    public JsonResult permissionAround(ProceedingJoinPoint joinPoint) {

        // 获取session的值
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpSession session = requestAttributes.getRequest().getSession();
        SessionUser sessionUser = (SessionUser)session.getAttribute("userinfo");

        // 获取被代理类的注解信息
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        HasPermission annotation = method.getAnnotation(HasPermission.class);
        String value = annotation.value();

        // 查看登录user是否有访问指定画面的权限
        String[] menuIdsArray = sessionUser.getMenuIds().split("/");
        boolean contains = Arrays.asList(menuIdsArray).contains(value);
        if (contains) {
            JsonResult result = null;
            try {
                result = (JsonResult)joinPoint.proceed();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            return result;
        } else {
            throw new NotHasPermissionException(2, "您没有访问该画面的权限");
        }

    }

}
